# Contributor: Mehdi Chinoune <mehdi.chinoune@hotmail.com>

_realname=mold
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=1.9.0
pkgrel=1
pkgdesc="A Modern Linker (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url='https://github.com/rui314/mold'
license=('AGPL3')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-libwinpthread-git"
         "${MINGW_PACKAGE_PREFIX}-mimalloc"
         "${MINGW_PACKAGE_PREFIX}-tbb"
         "${MINGW_PACKAGE_PREFIX}-zlib"
         "${MINGW_PACKAGE_PREFIX}-zstd")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=("${_realname}-${pkgver}.tar.gz::https://github.com/rui314/mold/archive/v${pkgver}.tar.gz"
        "001-support-mingw.patch")
sha256sums=('faf381ba268e714bec7f872de0dd6ea9187ae20b4e12c434a67ac92854701280'
            '5100b72a33205884d6ad1121921ec37f81de8a2aedb2066504590155c05ef3de')

prepare() {
  cd "${srcdir}"/${_realname}-${pkgver}
  patch -p1 -i "${srcdir}"/001-support-mingw.patch
}

build() {
  mkdir -p "${srcdir}/build-${MSYSTEM}" && cd "${srcdir}/build-${MSYSTEM}"

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    "${MINGW_PREFIX}"/bin/cmake.exe \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      -DCMAKE_INSTALL_LIBEXECDIR='lib' \
      "${_extra_config[@]}" \
      -DMOLD_USE_SYSTEM_MIMALLOC=ON \
      -DMOLD_USE_SYSTEM_TBB=ON \
      -DBUILD_TESTING=OFF \
      ../${_realname}-${pkgver}

  "${MINGW_PREFIX}"/bin/cmake.exe --build .
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"

  "${MINGW_PREFIX}"/bin/cmake -DBUILD_TESTING=ON ../${_realname}-${pkgver}
  "${MINGW_PREFIX}"/bin/cmake --build .
  "${MINGW_PREFIX}"/bin/ctest --output-on-failure
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"

  DESTDIR="${pkgdir}" "${MINGW_PREFIX}"/bin/cmake.exe --install .
}
